package com.iculture;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Hashtable;
import java.util.Locale;

import com.matchcalendar.R;

import activities.GlobalActivity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

public class SearchActivity extends GlobalActivity {
	private Spinner activity_type;
	private EditText search_text;
	private Button start_date, end_date, submit;
	private CheckBox check_pay, check_free;
	private ProgressDialog progDlg;
	private int type_value = 99;
	private int pay_type = 99;
	private String start_date_text,end_date_text;
	private Calendar matchStartCal = Calendar.getInstance();
	private Calendar matchEndCal = Calendar.getInstance();
	private String result_json;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_search);
		initGlobalView();
		setupViewComponent();
		setupSpinner();
	}

	private void setupViewComponent() {
		activity_type = (Spinner) findViewById(R.id.iculture_type_spinner);
		search_text = (EditText) findViewById(R.id.iculture_seaarch_text);
		check_pay = (CheckBox) findViewById(R.id.iculture_search_pay1);
		check_free = (CheckBox) findViewById(R.id.iculture_search_pay2);
		start_date= (Button) findViewById(R.id.buttonActivityStartTime);
		end_date= (Button) findViewById(R.id.buttonActivityOverTime);
		submit = (Button) findViewById(R.id.iculture_search_submit);
		submit.setOnClickListener(new submitClick());
		check_pay.setChecked(true);
		check_free.setChecked(true);
		check_pay.setOnCheckedChangeListener(chklistener);
		check_free.setOnCheckedChangeListener(chklistener);
		start_date.setOnClickListener(new ButtonStartDateClickListener());
		end_date.setOnClickListener(new ButtonOverDateClickListener());
		
		search_text.setText("莫札特");

	}

	private CheckBox.OnCheckedChangeListener chklistener = new CheckBox.OnCheckedChangeListener() {

		@Override
		public void onCheckedChanged(CompoundButton buttonView,
				boolean isChecked) {
			// 99:兩者皆勾選,0:免費,1:付費,9:都沒選
			if (check_pay.isChecked() && check_free.isChecked())
				pay_type = 99;
			else if (!check_pay.isChecked() && check_free.isChecked())
				pay_type = 0;
			else if (check_pay.isChecked() && !check_free.isChecked())
				pay_type = 1;
			else
				pay_type = 9;
			;
		}

	};
private class ButtonStartDateClickListener implements Button.OnClickListener {
		
		@Override
		public void onClick(View v) {
			DatePicker startDatePicker = new DatePicker(SearchActivity.this);
			
			startDatePicker.init(matchStartCal.get(Calendar.YEAR), matchStartCal.get(Calendar.MONTH), matchStartCal.get(Calendar.DATE), null);
			startDatePicker.setCalendarViewShown(false);
			new AlertDialog.Builder(SearchActivity.this)
			.setTitle("選擇範圍起始日期")
			.setView(startDatePicker)
			.setNegativeButton("取消", null)
			.setPositiveButton("確定", new StartDatePickerDialogPositiveClickListener(startDatePicker))
			.show();
		}
		
		private class StartDatePickerDialogPositiveClickListener implements DialogInterface.OnClickListener {
			private DatePicker startDatePicker;

			public StartDatePickerDialogPositiveClickListener(DatePicker startDatePicker) {
				this.startDatePicker = startDatePicker;
			}

			@Override
			public void onClick(DialogInterface dialog, int which) {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd", Locale.getDefault());
				
				matchStartCal.set(startDatePicker.getYear(), startDatePicker.getMonth(), startDatePicker.getDayOfMonth());
				start_date.setText(sdf.format(matchStartCal.getTime()));
				start_date_text=(sdf.format(matchStartCal.getTime()));
				//isComplete.add(buttonStartDate);
			}
		}
	}
	
	private class ButtonOverDateClickListener implements Button.OnClickListener {

		@Override
		public void onClick(View v) {
			DatePicker endDatePicker = new DatePicker(SearchActivity.this);
			
			endDatePicker.init(matchEndCal.get(Calendar.YEAR), matchEndCal.get(Calendar.MONTH), matchEndCal.get(Calendar.DATE), null);
			endDatePicker.setCalendarViewShown(false);
			new AlertDialog.Builder(SearchActivity.this)
			.setTitle("選擇範圍結束日期")
			.setView(endDatePicker)
			.setNegativeButton("取消", null)
			.setPositiveButton("確定", new OverDatePickerDialogPositiveClickListener(endDatePicker))
			.show();
		}
		
		private class OverDatePickerDialogPositiveClickListener implements DialogInterface.OnClickListener {
			private DatePicker endDatePicker;

			public OverDatePickerDialogPositiveClickListener(DatePicker endDatePicker) {
				this.endDatePicker = endDatePicker;
			}

			@Override
			public void onClick(DialogInterface dialog, int which) {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd", Locale.getDefault());
				
				matchEndCal.set(endDatePicker.getYear(), endDatePicker.getMonth(), endDatePicker.getDayOfMonth());
				end_date.setText(sdf.format(matchEndCal.getTime()));
				end_date_text=sdf.format(matchEndCal.getTime());
				//isComplete.add(buttonOverDate);
			}
		}
	}

	private class submitClick implements Button.OnClickListener {

		@Override
		public void onClick(View v) {
			progDlg = new ProgressDialog(SearchActivity.this);
			progDlg.setMessage(getString(R.string.loadingtxt));
			progDlg.setIcon(android.R.drawable.ic_dialog_info);
			progDlg.setCancelable(false);
			progDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progDlg.setMax(100);
			progDlg.show();
			new Thread(new Runnable() {
				public void run() {
					executeAsyncTask();
				}
			}).start();
		}
	}

	private void setupSpinner() {
		ArrayAdapter<CharSequence> activity_list = ArrayAdapter
				.createFromResource(this, R.array.search_array,
						android.R.layout.simple_spinner_dropdown_item);
		activity_type.setAdapter(activity_list);
		activity_type.setOnItemSelectedListener(spnActItemSelLis);
	}

	private Spinner.OnItemSelectedListener spnActItemSelLis = new Spinner.OnItemSelectedListener() {
		@Override
		public void onItemSelected(AdapterView parent, View v, int position,
				long id) {
			// 1音樂,5獨立音樂,6展覽,2戲劇,3舞蹈,4親子,17演唱會
			int[] activity_parse = { 99, 1, 5, 6, 2, 3, 4, 17 };
			type_value = activity_parse[parent.getSelectedItemPosition()];

		}

		@Override
		public void onNothingSelected(AdapterView parent) {
			// TODO Auto-generated method stub

		}
	};

	private class GetDataAyncTask extends
			AsyncTask<Hashtable<String, String>, Void, String> {

		@Override
		protected String doInBackground(Hashtable<String, String>... params) {
			Hashtable ht = params[0];

			String json = HelperHttp.getJSONResponseFromURL(
					"activity_querry.php", ht);
			if (json != null) {
				// DataList = data.parseJsonString(json);
				progDlg.setProgress(100);
				progDlg.cancel();
				result_json=json;
			} else {
				return "Invalid Param";
			}
			return "SUCCESS";
		}

		@Override
		protected void onPostExecute(String result) {
			if (result == "SUCCESS") {
				Toast.makeText(SearchActivity.this, "搜尋回傳成功!",
						Toast.LENGTH_SHORT).show();
				Intent it = new Intent(SearchActivity.this, Search_Result.class);
				Bundle bundle=new Bundle();
				bundle.putString("SEARCH_RESULUT", result_json);
				it.putExtras(bundle);
				startActivity(it);		
			}
			else {
				Toast.makeText(SearchActivity.this, "回傳資料錯誤!",
						Toast.LENGTH_SHORT).show();
			}

		}
	}

	private void executeAsyncTask() {
		Hashtable<String, String> ht = new Hashtable<String, String>();
		GetDataAyncTask async = new GetDataAyncTask();
		/*
		 * Bundle bundle=getIntent().getExtras();
		 * activity_value=bundle.getInt("ACT_VALUE");
		 */
		// ht.put("type", String.valueOf(activity_value));// 設定json url搜尋參數
		ht.put("title", search_text.getText().toString());
		ht.put("type", String.valueOf(type_value));
		ht.put("pay", String.valueOf(pay_type));
		ht.put("start_date", String.valueOf(start_date_text));
		ht.put("end_date", String.valueOf(end_date_text));
		Hashtable[] ht_array = { ht };
		async.execute(ht_array);
	}
}